package com.ljw.serialport;

import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SocketClient {
    public static final String IP = "192.168.1.25";
    public static final int PORT = 8080;

    Socket tcpclient;

    private static SocketClient socketClient=new SocketClient();

    public  static SocketClient getInstance(){
        return socketClient;
    }

    private SocketClient() {

    }
    private Socket createClient(String ip,int port){
        try {
            Socket  client = new Socket();
            client.connect(new InetSocketAddress(ip,port),500);
            return client;
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("SocketClient", "创建 Socket 失败");
        }
        return null;
    }

    //发送数据
    public boolean sendData(byte[] data) {
        if (tcpclient == null || !tcpclient.isConnected()) {
            tcpclient  = createClient(IP, PORT);
        }
        if (tcpclient==null||!tcpclient.isConnected()||tcpclient.isClosed()){
            return false;
        }
        try {
            OutputStream outputStream = tcpclient.getOutputStream();
            outputStream.write(data);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            close();
        }
        return true;
    }

    public void close() {
        if (tcpclient != null) {
            try {
                tcpclient.close();
                tcpclient=null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 16进制字符串转为16进制
     * @param hex 16进制的字符串
     * @return
     */
    public static byte[] hexString2Bytes(String hex) {
        hex=hex.replace(" ","").trim();
        if ((hex == null) || (hex.equals(""))){
            return null;
        }
        else if (hex.length()%2 != 0){
            return null;
        }
        else{
            hex = hex.toUpperCase();
            int len = hex.length()/2;
            byte[] b = new byte[len];
            char[] hc = hex.toCharArray();
            for (int i=0; i<len; i++){
                int p=2*i;
                b[i] = (byte) (charToByte(hc[p]) << 4 | charToByte(hc[p+1]));
            }
            return b;
        }
    }
    /*
     * 字符转换为字节
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}
